#include "chatclient.h"

chatclient::chatclient(QObject *parent) : QObject(parent),socket(nullptr)
{

}

chatclient::~chatclient()
{
    this->stopClient();
}

/* 开启客户端 连接的远程蓝牙服务 */
void chatclient::startClient(const QBluetoothServiceInfo &remoteService)
{
    if(this->socket)
        return;

    // 创建了一个用于基于蓝牙的串行通信的套接字对象
    // QBluetoothServiceInfo::RfcommProtocol表示使用蓝牙串行通信协议（RFCOMM）
    this->socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);

    qDebug() << "Create socket";
    // 将套接字连接到指定的远程服务
    socket->connectToService(remoteService);
    qDebug() << "ConnectToService done";
    connect(socket, SIGNAL(readyRead()),this, SLOT(readSocket()));
    connect(socket, SIGNAL(connected()),this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()),this, SIGNAL(disconnected()));
}

/* 停止客户端 */
void chatclient::stopClient()
{
    delete socket;
    socket = nullptr;
}

/* 发送的消息 */
void chatclient::sendMessage(const QString &message)
{
    qDebug()<<"Sending data in client: " + message;

    // 代码使用套接字的write函数将字节数组写入套接字，实现将消息发送给远程服务
    QByteArray text = message.toUtf8() + '\n';
    socket->write(text);
}

/* 从 Socket 读取消息 */
void chatclient::readSocket()
{
    // 代码检查套接字对象是否存在，如果不存在，则直接返回
    if (!socket)
        return;

    // 代码使用canReadLine函数检查是否可以从套接字中读取一行数据
     while (socket->canReadLine()) {
         QByteArray line = socket->readLine();
         emit sig_messageReceived(socket->peerName(),QString::fromUtf8(line.constData(),line.length()));
     }
}

/* 主动断开连接*/
void chatclient::disconnect()
{
    qDebug()<<"Going to disconnect in client";
    if (socket) {
        qDebug()<<"diconnecting...";
        socket->close();
    }
}

/* 主动连接 */
void chatclient::connected()
{
   emit sig_connected(socket->peerName());
}
